package islandPerimeter;

public class Solution {
    public int islandPerimeter(int[][] grid) {
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if(grid[i][j]==1){
                    res+=check(i,j,grid);
                }
            }
        }
        return res;
    }
    // 返回这个格子的周长
    private int check(int i,int j,int [][]grid){
        int res = 4;
        if(i>0){
            if(grid[i-1][j]==1){
                res--;
            }
        }
        if(i<grid.length-1){
            if(grid[i+1][j]==1){
                res--;
            }
        }
        if(j>0){
            if(grid[i][j-1]==1){
                res--;
            }
        }
        if(j<grid[i].length-1){
            if(grid[i][j+1]==1){
                res--;
            }
        }
        return res;
    }
}
